﻿using BitButterECS.Event;
using BitButterECS.Event.EventArgs;

namespace BitButterECS.System
{
    public abstract class BaseSystem
    {
        public BaseSystem()
        {
            RegisterEventHandlers();
            Manager.AddSystem(this);
        }

        protected virtual void RegisterEventHandlers()
        {
            AttachComponentEvent.Handler += OnAttachComponentEvent;
            DetachComponentEvent.Handler += OnDetachComponentEvent;
        }

        protected virtual void UnregisterEventHandlers()
        {
            AttachComponentEvent.Handler -= OnAttachComponentEvent;
            DetachComponentEvent.Handler -= OnDetachComponentEvent;
        }

        protected virtual void OnAttachComponentEvent(object sender, AttachComponentEventArgs e)
        {
        }

        protected virtual void OnDetachComponentEvent(object sender, DetachComponentEventArgs e)
        {
        }

        public int ID
        {
            get => id;
            set
            {
                if (!IsManaged)
                {
                    id = value;
                }
            }
        }
        int id = -1;

        public bool IsManaged => Manager.HasSystem(this);

        public virtual void Remove()
        {
            UnregisterEventHandlers();
            Manager.RemoveSystem(this);
        }

        public bool IsEnabled { get; set; } = true;

        protected SystemManager Manager => SystemManager.Instance;
    }
}
